package com.aj.activity.fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.aj.activity.R;
import com.aj.activity.dialog.InfoDialog;
import com.aj.activity.dialog.InfoDialog.IInfoInterface;
import com.aj.activity.dialog.LogoutDialog;
import com.aj.activity.dialog.LogoutDialog.ILogoutInterface;
import com.aj.activity.dialog.ProgressDialog;
import com.aj.activity.dialog.UpdateDialog;
import com.aj.activity.dialog.UpdateDialog.IUpdateDialog;
import com.aj.activity.view.CircleImageView;
import com.aj.application.LoveHomeApplication;
import com.aj.databases.dao.AccountDao;
import com.aj.databases.dao.UserDao;
import com.aj.databases.entry.Account;
import com.aj.databases.entry.User;
import com.aj.databases.entry.VersionInfo;
import com.aj.http.AsynchronizationHttpRequest.IHttpCallBack;
import com.aj.http.request.UpdateRequest;
import com.aj.http.response.BaseRespond;
import com.aj.http.response.UpdateResponse;
import com.aj.sharepreferences.LoveHomeSharedPreferences;
import com.aj.utils.Contants;
import com.aj.utils.MobileUtil;
import com.aj.utils.PortraitLoaderUtil;
import com.aj.utils.StringUtils;

/**
 * A simple {@link Fragment} subclass.
 */
public class SettingsFragment extends Fragment implements ILogoutInterface {

	private static final String TAG = SettingsFragment.class.getName();

	private LogoutDialog dialog;

	private UpdateDialog updateDialog;

	private TextView datamanage;

	private TextView register_text;

	private TextView update_check;

	private TextView login_text;

	private TextView homesafe;

	private TextView clear;

	private TextView about;

	private TextView recommend_friend;

	private TextView qrcodedownload;

	private LinearLayout nologin_linearlayout;

	private LinearLayout login_linearlayout;

	private VersionInfo versionInfo;

	private CircleImageView head_img;

	private TextView username_text;

	private TextView mycreathome;

	private ToggleButton switchbutton;

	private TextView personalsignature_text;

	private LinearLayout tools_linearlayout;

	private ImageView goto_edit;

	private InfoDialog infoDialog;

	private ProgressDialog progressDialog;

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private String saveFileName;

	private Thread downLoadThread;

	private ProgressBar mProgress;

	private boolean interceptFlag = false;

	private AlertDialog downloadDialog;

	private void showProgressDialog() {
		showProgressDialog(R.string.data_loading_text);
	}

	private void showProgressDialog(String message) {
		if (progressDialog == null) {
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.show();
			progressDialog.setContentText(message);
		}
	}

	private void showProgressDialog(int messageId) {
		if (progressDialog == null) {
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.show();
			progressDialog.setContentText(getString(messageId));
		}
	}

	private void dimmissProgressDialog() {
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	private void showInfoDialog(String message, String okText,
			String cannelText, IInfoInterface infoInterface) {
		if (infoDialog == null) {
			infoDialog = new InfoDialog(getActivity());
		}
		infoDialog.show();
		infoDialog.setContent(message);
		infoDialog.setSureButtonText(okText);
		infoDialog.setCannelButtonText(cannelText);
		infoDialog.setInfoInterface(infoInterface);
	}

	private void initVisibleView(boolean isLogin) {
		if (isLogin) {
			nologin_linearlayout.setVisibility(View.GONE);
			login_linearlayout.setVisibility(View.VISIBLE);
			goto_edit.setVisibility(View.VISIBLE);
			// tools_linearlayout.setVisibility(View.VISIBLE);
		} else {
			nologin_linearlayout.setVisibility(View.VISIBLE);
			head_img.setImageResource(R.drawable.head_icon);
			login_linearlayout.setVisibility(View.GONE);
			goto_edit.setVisibility(View.GONE);
			// tools_linearlayout.setVisibility(View.GONE);
		}
	}

	public SettingsFragment() {
	}

	@Override
	public void onResume() {
		super.onResume();
		// initVisibleView(LoveHomeApplication.token != null
		// && LoveHomeApplication.token.trim().length() > 0);
		initUserInfo();
	}

	private void initUserInfo() {
		if (LoveHomeApplication.token != null
				&& LoveHomeApplication.token.trim().length() > 0) {
			AccountDao accountDao = new AccountDao(getActivity());
			UserDao userDao = new UserDao(getActivity());
			Account account = accountDao.getByToken(LoveHomeApplication.token);
			if (account != null) {
				User user = userDao.getUserByUserId(account
						.getLast_used_user_id());
				if (user != null) {
					username_text.setText(user.getNickName());
					personalsignature_text.setText(user.getSign());
					PortraitLoaderUtil.load(getActivity(), head_img,
							user.getPortrait_path(), user.getPortrait_url(),
							R.drawable.head_icon, R.drawable.head_icon);
					initVisibleView(true);
				} else {
					initVisibleView(false);
				}
			} else {
				initVisibleView(false);
			}
		} else {
			initVisibleView(false);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_settings, container,
				false);
		ShareSDK.initSDK(getActivity());
		initView(view);
		return view;
	}

	private void initView(View view) {
		datamanage = (TextView) view.findViewById(R.id.datamanage);
		register_text = (TextView) view.findViewById(R.id.register_text);
		update_check = (TextView) view.findViewById(R.id.update_check);
		login_text = (TextView) view.findViewById(R.id.login_text);
		homesafe = (TextView) view.findViewById(R.id.homesafe);
		clear = (TextView) view.findViewById(R.id.clear);
		recommend_friend = (TextView) view.findViewById(R.id.recommend_friend);
		qrcodedownload = (TextView) view.findViewById(R.id.qrcodedownload);
		head_img = (CircleImageView) view.findViewById(R.id.head_img);
		about = (TextView) view.findViewById(R.id.about);
		nologin_linearlayout = (LinearLayout) view
				.findViewById(R.id.nologin_linearlayout);
		login_linearlayout = (LinearLayout) view
				.findViewById(R.id.login_linearlayout);
		username_text = (TextView) view.findViewById(R.id.username_text);
		mycreathome = (TextView) view.findViewById(R.id.mycreathome);
		personalsignature_text = (TextView) view
				.findViewById(R.id.personalsignature_text);
		switchbutton = (ToggleButton) view.findViewById(R.id.switchbutton);

		switchbutton.setChecked(LoveHomeSharedPreferences.getWifiFlag());

		switchbutton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				LoveHomeSharedPreferences.insertWifiFlag(isChecked);
			}
		});

		tools_linearlayout = (LinearLayout) view
				.findViewById(R.id.tools_linearlayout);
		goto_edit = (ImageView) view.findViewById(R.id.goto_edit);

		ClickEvent clickEvent = new ClickEvent();
		datamanage.setOnClickListener(clickEvent);
		register_text.setOnClickListener(clickEvent);
		login_text.setOnClickListener(clickEvent);
		homesafe.setOnClickListener(clickEvent);
		qrcodedownload.setOnClickListener(clickEvent);
		clear.setOnClickListener(clickEvent);
		update_check.setOnClickListener(clickEvent);
		recommend_friend.setOnClickListener(clickEvent);
		about.setOnClickListener(clickEvent);
		mycreathome.setOnClickListener(clickEvent);
	}

	class ClickEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			Intent intent = null;
			UserDao userDao = new UserDao(getActivity());
			switch (v.getId()) {
			case R.id.clear:
				showInfoDialog(getString(R.string.is_clear_file),
						getString(R.string.dialog_sure_text),
						getString(R.string.dialog_cannel_text),
						new IInfoInterface() {
							@Override
							public void sureInfo() {
								showProgressDialog(getString(R.string.local_clear_load_text));
								new ClearTask(getActivity())
										.execute(new Void[] { null });
							}

							@Override
							public void cannelInfo() {

							}
						});
				break;
			case R.id.datamanage:
				if (LoveHomeApplication.token == null
						|| LoveHomeApplication.token.trim().length() == 0) {
					intent = new Intent(Contants.LOGINACTIVITY_ACTION);
					startActivity(intent);
					break;
				}

				User user = userDao.getCurrentUser(LoveHomeApplication.token);
				if (user != null) {
					intent = new Intent(Contants.USERINFO_ACTIVITY_ACTION);
					intent.putExtra(Contants.USERINFOFLAG_STRING, user);
					startActivity(intent);
				} else {
					Toast.makeText(getActivity(),
							getString(R.string.local_login_info_error_text),
							Toast.LENGTH_LONG).show();
					LoveHomeApplication.token = "";
					initVisibleView(false);
				}

				break;
			case R.id.register_text:
				intent = new Intent(Contants.ENTER_PHONE_ACTION);
				intent.putExtra(Contants.PAGEFLAG_STRING,
						Contants.REGISTER_PAGEFLAG_STRING);
				startActivity(intent);
				break;
			case R.id.login_text:
				intent = new Intent(Contants.LOGINACTIVITY_ACTION);
				startActivity(intent);
				break;
			case R.id.homesafe:
				if (LoveHomeApplication.token == null
						|| LoveHomeApplication.token.trim().length() == 0) {
					intent = new Intent(Contants.LOGINACTIVITY_ACTION);
					startActivity(intent);
					break;
				}
				intent = new Intent(Contants.SAFE_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			case R.id.qrcodedownload:
				intent = new Intent(Contants.QRCODE_DOWNLOAD_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			case R.id.about:
				intent = new Intent(Contants.ABOUT_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			case R.id.mycreathome:
				if (LoveHomeApplication.token == null
						|| LoveHomeApplication.token.trim().length() == 0) {
					intent = new Intent(Contants.LOGINACTIVITY_ACTION);
					startActivity(intent);
					break;
				}
				user = userDao.getCurrentUser(LoveHomeApplication.token);
				if (user != null) {
					intent = new Intent(Contants.OPINION_ACTIVITY_ACTION);
					intent.putExtra(Contants.USERINFOUSERID_STRING,
							user.getUser_id());
					startActivity(intent);
				} else {
					Toast.makeText(getActivity(),
							getString(R.string.local_login_info_error_text),
							Toast.LENGTH_LONG).show();
					LoveHomeApplication.token = "";
					initVisibleView(false);
				}
				break;
			case R.id.update_check:
				showProgressDialog();
				UpdateRequest updateRequest = new UpdateRequest();
				updateRequest.excute(getActivity(),
						MobileUtil.getVersionName(getActivity()),
						new IHttpCallBack() {
							@Override
							public void success(String result) {
								dimmissProgressDialog();
								try {
									UpdateResponse updateResponse = new UpdateResponse(
											new JSONObject(result));
									if (updateResponse
											.getCommon()
											.getReturnCode()
											.equals(BaseRespond.SUCCESS_RESULT_CODE_STRING)) {
										versionInfo = updateResponse
												.getVersionInfo();
										String versionID = versionInfo
												.getClientVer();
										if (StringUtils.compare(
												versionID,
												MobileUtil
														.getVersionName(getActivity())) > 1) {
											String message = versionInfo
													.getUpdateContent() == null
													|| versionInfo
															.getUpdateContent()
															.trim().length() == 0 ? getString(R.string.no_updateinfo_text)
													: versionInfo
															.getUpdateContent();
											showUpdateDialog(
													message,
													(versionInfo
															.getForceUpdate() == null
															|| versionInfo
																	.getForceUpdate()
																	.trim()
																	.equals("N") ? false
															: true));
										}
									} else {
										// TODO 弹出提示框
										showInfoDialog(
												getString(R.string.no_update_info_text),
												getString(R.string.know_button_text),
												getString(R.string.dialog_cannel_text),
												null);
									}
								} catch (JSONException e) {
									Log.e(TAG, "ERROR:" + result, e);
									e.printStackTrace();
								}
							}

							@Override
							public void fail(String result) {
								dimmissProgressDialog();
								Log.e(TAG, "ERROR:" + result);
							}
						});
				break;
			case R.id.recommend_friend:
				if (LoveHomeApplication.token == null
						|| LoveHomeApplication.token.trim().length() == 0) {
					intent = new Intent(Contants.LOGINACTIVITY_ACTION);
					startActivity(intent);
					break;
				}
				showShare();
				break;
			}
		}
	}

	@Override
	public void sureLogout() {
		getActivity().finish();
		System.exit(0);
	}

	class ClearTask extends AsyncTask<Void, Void, Long> {
		private Context context;

		public ClearTask(Context context) {
			this.context = context;
		}

		/**
		 * 运行在UI线程中，在调用doInBackground()之前执行
		 */
		@Override
		protected void onPreExecute() {
		}

		/**
		 * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
		 */
		@Override
		protected Long doInBackground(Void... params) {
			if (isCancelled()) {
				return null;
			}
			String imagesPath = getFilePath() + Contants.IMAGE_PATH_STRING;
			String soundRecordFilePath = getFilePath()
					+ Contants.SOUND_PATH_STRING;
			String photoRecordFilePath = getFilePath()
					+ Contants.HEADER_IMAGE_PATH_STRING;
			String dirFilePath = getFilePath();
			File imagePathFile = new File(imagesPath);
			File soundRecordFile = new File(soundRecordFilePath);
			File photoRecordFile = new File(photoRecordFilePath);
			File dirFile = new File(dirFilePath);
			Long fileSize = 0L;
			long tempFileSize = 0;
			if (dirFile.exists()) {
				File[] dirFileList = dirFile.listFiles();
				for (File tempFile : dirFileList) {
					tempFileSize = tempFile.length();
					if (tempFile.isFile() && tempFile.delete()) {
						fileSize += tempFileSize;
					}
				}
			}
			if (photoRecordFile.exists()) {
				File[] photoFileList = photoRecordFile.listFiles();
				for (File tempFile : photoFileList) {
					tempFileSize = tempFile.length();
					if (tempFile.isFile() && tempFile.delete()) {
						fileSize += tempFileSize;
					}
				}
			}
			if (imagePathFile.exists()) {
				File[] cashLogFileList = imagePathFile.listFiles();
				for (File tempFile : cashLogFileList) {
					tempFileSize = tempFile.length();
					if (tempFile.isFile() && tempFile.delete()) {
						fileSize += tempFileSize;
					}
				}
			}
			if (soundRecordFile.exists()) {
				File[] soundRecordFileList = soundRecordFile.listFiles();
				for (File tempFile : soundRecordFileList) {
					tempFileSize = tempFile.length();
					if (tempFile.isFile() && tempFile.delete()) {
						fileSize += tempFileSize;
					}
				}
			}
			return fileSize;
		}

		/**
		 * 运行在ui线程中，在doInBackground()执行完毕后执行
		 */
		@Override
		protected void onPostExecute(Long fileSize) {
			String message = "";
			if (fileSize.equals(0L)) {
				message = getString(R.string.local_nocache_text);
			} else {
				String tempMessage = "";
				if (fileSize < 1024) {
					tempMessage = fileSize + "B";
				} else if (fileSize >= 1024 && fileSize < 1024 * 1024) {
					DecimalFormat df = new DecimalFormat("#.###");
					tempMessage = df.format((fileSize / 1024f)) + "KB";
				} else {
					DecimalFormat df = new DecimalFormat("#.###");
					tempMessage = df.format(((fileSize / 1024f) / 1024f))
							+ "MB";
				}
				message = getString(R.string.local_cache_text) + tempMessage;
			}
			dimmissProgressDialog();
			showInfoDialog(message,
					fileSize.equals(0L) ? getString(R.string.know_button_text)
							: getString(R.string.tanks_button_text),
					getString(R.string.dialog_cannel_text), null);
		}

		/**
		 * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
		 */
		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	private String getFilePath() {
		String file_dir = "";
		// SD卡是否存在
		boolean isSDCardExist = Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState());
		// Environment.getExternalStorageDirectory()相当于File file=new
		// File("/sdcard")
		boolean isRootDirExist = Environment.getExternalStorageDirectory()
				.exists();
		if (isSDCardExist && isRootDirExist) {
			file_dir = Contants.APP_PATH;
		} else {
			// MyApplication.getInstance().getFilesDir()返回的路劲为/data/data/PACKAGE_NAME/files，其中的包就是我们建立的主Activity所在的包
			file_dir = LoveHomeApplication.application.getFilesDir()
					.getAbsolutePath();
		}
		return file_dir;
	}

	private void showUpdateDialog(String message, final boolean isForceUpdate) {
		if (updateDialog == null) {
			updateDialog = new UpdateDialog(getActivity());
		}
		updateDialog.show();
		updateDialog.setContent(message);
		updateDialog.setUpdateDialogInterface(new IUpdateDialog() {
			@Override
			public void sureInfo() {
				// TODO 下载APP
				showDownloadDialog();
			}

			@Override
			public void cannelInfo() {
				if (isForceUpdate) {
					getActivity().finish();
				} else {
				}
			}
		});
	}

	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setTitle("软件版本更新中");
		final LayoutInflater inflater = LayoutInflater.from(getActivity());
		View v = inflater.inflate(R.layout.dialog_update_process, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);
		builder.setView(v);
		downloadDialog = builder.create();
		downloadDialog.setCancelable(false);
		downloadDialog.show();
		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(versionInfo.getClientUrl());

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				InputStream is = conn.getInputStream();
				long fileSize = Long.parseLong(conn
						.getHeaderField("Content-length") == null ? "1" : conn
						.getHeaderField("Content-length").toString());
				long length = fileSize;
				File file = new File(Contants.APP_PATH);
				if (!file.exists()) {
					file.mkdir();
				}
				saveFileName = Contants.APP_PATH + "LoveHome.apk";
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				if (ApkFile.exists()) {
					ApkFile.delete();
				}
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						interceptFlag = true;
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		this.startActivity(i);
		android.os.Process.killProcess(android.os.Process.myPid());

	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	private void showShare() {
		OnekeyShare oks = new OnekeyShare();
		// 分享时Notification的图标和文字
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		oks.setTitle(getString(R.string.app_name));
		oks.setText("爱家APP，让你更快更便捷的了解家人动向~");
		oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/05/21/oESpJ78_533x800.jpg");
		// 启动分享GUI
		oks.show(getActivity());
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		ShareSDK.stopSDK(getActivity());
	}
}
